package com.cloud.service.impl;

import com.alibaba.fastjson.JSON;
import com.cloud.consumer.ConsumerMqListener;
import com.cloud.convertor.CloudLogRecordConvertor;
import com.cloud.dto.CloudLogRecordReqQuery;
import com.cloud.entity.CloudLogRecord;
import com.cloud.entity.HbaseEntity;
import com.cloud.entity.SysLog;
import com.cloud.mapper.CloudLogRecordMapper;
import com.cloud.rest.PageInfoRes;
import com.cloud.service.CloudLogRecordService;
import com.cloud.utils.HBaseUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class CloudLogRecordServiceImpl implements CloudLogRecordService {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");

    @Autowired
    private CloudLogRecordMapper cloudLogRecordMapper;

    @Autowired
    private ConsumerMqListener consumerListener;

    @Autowired
    private HBaseUtils hBaseUtils;

    @Autowired
    private CloudLogRecordConvertor cloudLogRecordConvertor;

    public volatile static Long sum = 0L;

    /**
     * 将日志插入到hbase或者mysql数据库中
     *
     * @param cloudLogMap
     * @return void
     */
    @SneakyThrows
    @Override
    public void saveBatchLog(Map<String, List<CloudLogRecord>> cloudLogMap) {
        //cloudLogMap等于空，代表当前线程读取map未达到指定条数，无需插入，快速返回
        if (cloudLogMap == null) {
            return;
        }
        for (Map.Entry<String, List<CloudLogRecord>> entry : cloudLogMap.entrySet()) {
            if (!CollectionUtils.isEmpty(entry.getValue()) && StringUtils.isNotBlank(entry.getKey())) {
//                    log.info("我插入了CloudLogRecord");
                String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                //当初将2022年11月16号之后的数据迁入到hbase
                if (Long.parseLong(date) > 20221116235900L) {
                    log.info("准备插入了hbase数据库");
                    //插入hbase
                    List<HbaseEntity> hbaseEntities = cloudLogRecordConvertor.convertList(entry.getValue());
                    hBaseUtils.insertDataList("cloud_log_record_" + entry.getKey().substring(0, 6), "logs", hbaseEntities);
                } else {
                    log.info("准备插入了mysql数据库");
                    cloudLogRecordMapper.saveBatchLog(entry.getValue(), "cloud_log_record_" + entry.getKey().substring(0, 6));
                }
            }
        }
        cloudLogMap.clear();
    }

    /**
     * 创建表
     *
     * @param tableName
     * @return void
     */
    @Override
    public void createTableIfAbsent(String tableName) {
        cloudLogRecordMapper.createTableIfAbsent(tableName);
    }

    @Override
    public PageInfoRes<CloudLogRecord> getCloudLogRecordPage(CloudLogRecordReqQuery cloudLogRecordReqQuery) {
        if (cloudLogRecordReqQuery == null) {
            return null;
        }
        PageHelper.startPage(cloudLogRecordReqQuery.getPage() != null ? cloudLogRecordReqQuery.getPage() : 1, cloudLogRecordReqQuery.getSize() != null ? cloudLogRecordReqQuery.getSize() : 10);
        String format = "";
        //如果时间没有传的话，就查本月的前多少条
        if (cloudLogRecordReqQuery.getBeginReqTime() == null && cloudLogRecordReqQuery.getEndReqTime() == null) {
            //只能查本月的
            format = sdf.format(new Date());
        }
        //如果开始时间不等于null
        else if (cloudLogRecordReqQuery.getBeginReqTime() != null) {
            format = sdf.format(cloudLogRecordReqQuery.getBeginReqTime());
        }
        //结束时间
        else if (cloudLogRecordReqQuery.getBeginReqTime() == null
                && cloudLogRecordReqQuery.getEndReqTime() != null) {
            format = sdf.format(cloudLogRecordReqQuery.getEndReqTime());
        }
        log.info("表名后缀：：：" + format);
        List<CloudLogRecord> cloudLogRecordList = cloudLogRecordMapper.getCloudLogRecordPage(cloudLogRecordReqQuery, "cloud_log_record_" + format);

        return PageInfoRes.build(new PageInfo<>(cloudLogRecordList));
    }

    @Override
    public PageInfoRes<Void> batchInsertLog(List<SysLog> sysLogs) {
        for (SysLog sysLog : sysLogs) {
            consumerListener.handlerCloudLogRecord(JSON.toJSONString(sysLog));
            consumerListener.handlerSyslogRecord(JSON.toJSONString(sysLog));
        }
        return null;
    }

    /**
     * mysql数据导入hbase
     *
     * @param tableName
     * @return Boolean
     */
    @Override
    public Boolean synHbase(String tableName, String size, String id) throws Exception {

        Long startId = Long.parseLong(id);
        Long endid = Long.parseLong(id) + Long.parseLong(size);

        Long maxid = Long.valueOf(cloudLogRecordMapper.getMaxId(tableName).getId());

        while (true) {

            Long startTime = System.currentTimeMillis();

            List<CloudLogRecord> cloudLogRecordList = cloudLogRecordMapper.selectAllById(tableName, startId, endid);
            startId = endid;
            endid = startId + Long.parseLong(size);
            if (!CollectionUtils.isEmpty(cloudLogRecordList)) {
                sum = sum + 1L;
                log.info("正在同步sync循环次数==::" + sum + ",sync线程==" + Thread.currentThread().getName());
                List<HbaseEntity> hbaseEntities = cloudLogRecordConvertor.convertList(cloudLogRecordList);
                hBaseUtils.insertDataListSync(tableName, "logs", hbaseEntities);
                log.info("正在同步，size=" + hbaseEntities.size() + ",同步一次使用的时间：：" + (System.currentTimeMillis() - startTime));
            }
            if (startId > maxid) {

                log.info("同步结束，插入的次数===" + sum);
                log.info("同步结束，最终的主键===" + endid);
                return null;
            }
        }
    }
}
